<?php

namespace app\tiktok\logic;
use think\facade\Db;
use app\common\library\Excel;
use app\order\logic\OrderLogic;
use app\data\util\HttpUtil;
use app\api\logic\ApiOrderLogic;

class AutoshippingLogic extends BasicLogic
{

    

    /**
     * @desc   自动发货列表
     * @author zhangheng
     * @date   2025-07-04
     */
    public function index($params=[]){
        $limit = $params['limit'] ?? 10;
        $type = $params['type'] ?? "";
        $deliver_no = $params['deliver_no'] ?? "";
        $created_time = $params['create_time'] ?? [];
        $where = [];

        $contact = $params['contact'] ?? "";
        if($contact){
            $where[] = ['contact', 'like', '%'.$contact.'%'];
        }

        $sku = $params['sku'] ?? "";
        if($sku){
            $where[] = ['sku', 'like', '%'.$sku.'%'];
        }

        if($deliver_no){
            $where[] = ['deliver_no', 'like', '%'.$deliver_no.'%'];
        }
        if(!empty($type) && $type !== 'All'){
            $where[] = ['type', '=', $type];
        }
        if(!empty($params['status']) && $params['status'] !== 'All'){
            $status = $params['status'] ?? 0;
            $where[] = ['status', '=', $status];
        }
        if(isset($params['status']) && $params['status'] == 0){
            $where[] = ['status', '=', 0];
        }

        if ($created_time) {
            if(is_array($created_time)){
                $where[]  = ['created_time', '>=', $created_time[0]];
                $where[]  = ['created_time', '<=', date('Y-m-d H:i:s', strtotime($created_time[1]) + 86399)];
            }
        }
        

        if (!empty($params['order_id']) && !empty(trim($params['order_id']))) {  
            $order_ids_raw = trim($params['order_id']);  
            $order_ids_filtered = array_filter(explode("\n", $order_ids_raw), 'trim');  
            if (!empty($order_ids_filtered)) {  
                $where[] = ['deliver_no', 'in', $order_ids_filtered];  
            }  
        }
        if (!empty($params['tracking_number']) && !empty(trim($params['tracking_number']))) {  
            $order_ids_raw = trim($params['tracking_number']);  
            $order_ids_filtered = array_filter(explode("\n", $order_ids_raw), 'trim');  
            if (!empty($order_ids_filtered)) {  
                $where[] = ['waybill_no', 'in', $order_ids_filtered];  
            }  
        }
        $admin = Db::name('system_admin')
            ->field('a.id,a.username')
            ->alias('a')
            ->join('qu_system_group_admin b','b.admin_id = a.id', 'left')
            // ->where('b.group_id',24)
            ->where('a.status',1)
            ->select()
            ->toarray();
        $admin_ids = array_column($admin,'username','id');

        $res   = Db::name('tik_auto_shipping')
            ->where($where)
            ->order('created_time desc')
            ->paginate($limit);
        $list = $res->items()?:[];
        foreach ($list as $k=>$v) {
            $list[$k]['username'] = $admin_ids[$v['admin_id']] ?? '--';
            $list[$k]['created_time'] = date('Y-m-d', strtotime($v['created_time']));
            switch ($list[$k]['status']) {
                case '0':
                    $list[$k]['status_msg'] = '等待发货';
                    break;
                case '1':
                    $list[$k]['status_msg'] = '回传物流单号';
                    break;
                case '2':
                    $list[$k]['status_msg'] = '发货成功';
                    break;
                case '3':
                    $list[$k]['status_msg'] = '发货失败';
                    break;
                case '4':
                    $list[$k]['status_msg'] = '取消发货';
                    break;
                default:
                    $list[$k]['status_msg'] = '等待发货';
            }
            switch ($list[$k]['type']) {
                case '1':
                    $list[$k]['type_msg'] = 'TK发货';
                    break;
                case '2':
                    $list[$k]['type_msg'] = 'KOL发货';
                    break;
                case '3':
                    $list[$k]['type_msg'] = '海拍发货';
                    break;
                case '4':
                    $list[$k]['type_msg'] = 'Billo';
                    break;
                default:
                    $list[$k]['type_msg'] = '';
            }
            switch ($v['warehouse_id']) {
                case '3':
                    $list[$k]['warehouse_name'] = 'DYY-LA';
                    break;
                case '4':
                    $list[$k]['warehouse_name'] = 'DYY-NY';
                    break;
                default:
                    $list[$k]['warehouse_name'] = '未知';
            }
            
            
        }
        

        $data = [
            'list'                         => $list,
            'total'                        => $res->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }


    

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $type = $params['type'] ?? "";
        $deliver_no = $params['deliver_no'] ?? "";
        $created_time = $params['create_time'] ?? [];
        $where = [];

        $contact = $params['contact'] ?? "";
        if($contact){
            $where[] = ['contact', 'like', '%'.$contact.'%'];
        }

        $sku = $params['sku'] ?? "";
        if($sku){
            $where[] = ['sku', 'like', '%'.$sku.'%'];
        }

        if($deliver_no){
            $where[] = ['deliver_no', 'like', '%'.$deliver_no.'%'];
        }
        if(!empty($type) && $type !== 'All'){
            $where[] = ['type', '=', $type];
        }
        if(!empty($params['status']) && $params['status'] !== 'All'){
            $status = $params['status'] ?? 0;
            $where[] = ['status', '=', $status];
        }
        if(isset($params['status']) && $params['status'] == 0){
            $where[] = ['status', '=', 0];
        }

        if ($created_time) {
            if(is_array($created_time)){
                $where[]  = ['created_time', '>=', $created_time[0]];
                $where[]  = ['created_time', '<=', date('Y-m-d H:i:s', strtotime($created_time[1]) + 86399)];
            }
        }
        

        if (!empty($params['order_id']) && !empty(trim($params['order_id']))) {  
            $order_ids_raw = trim($params['order_id']);  
            $order_ids_filtered = array_filter(explode("\n", $order_ids_raw), 'trim');  
            if (!empty($order_ids_filtered)) {  
                $where[] = ['deliver_no', 'in', $order_ids_filtered];  
            }  
        }
        if (!empty($params['tracking_number']) && !empty(trim($params['tracking_number']))) {  
            $order_ids_raw = trim($params['tracking_number']);  
            $order_ids_filtered = array_filter(explode("\n", $order_ids_raw), 'trim');  
            if (!empty($order_ids_filtered)) {  
                $where[] = ['waybill_no', 'in', $order_ids_filtered];  
            }  
        }
        $admin = Db::name('system_admin')
            ->field('a.id,a.username')
            ->alias('a')
            ->join('qu_system_group_admin b','b.admin_id = a.id', 'left')
            // ->where('b.group_id',24)
            ->where('a.status',1)
            ->select()
            ->toarray();
        $admin_ids = array_column($admin,'username','id');

        $list   = Db::name('tik_auto_shipping')
            ->where($where)
            ->order('created_time desc')
            ->select()->toarray();
        foreach ($list as $k=>$v) {
            $list[$k]['deliver_no'] = "订单号：".(string)$v['deliver_no'] . " ";
            $list[$k]['username'] = $admin_ids[$v['admin_id']] ?? '--';
            $list[$k]['created_time'] = date('Y-m-d', strtotime($v['created_time']));
            switch ($list[$k]['status']) {
                case '0':
                    $list[$k]['status_msg'] = '等待发货';
                    break;
                case '1':
                    $list[$k]['status_msg'] = '回传物流单号';
                    break;
                case '2':
                    $list[$k]['status_msg'] = '发货成功';
                    break;
                case '3':
                    $list[$k]['status_msg'] = '发货失败';
                    break;
                case '4':
                    $list[$k]['status_msg'] = '取消发货';
                    break;
                default:
                    $list[$k]['status_msg'] = '等待发货';
            }
            switch ($list[$k]['type']) {
                case '1':
                    $list[$k]['type_msg'] = 'TK发货';
                    break;
                case '2':
                    $list[$k]['type_msg'] = 'KOL发货';
                    break;
                case '3':
                    $list[$k]['type_msg'] = '海拍发货';
                    break;
                case '4':
                    $list[$k]['type_msg'] = 'Billo';
                    break;
                default:
                    $list[$k]['type_msg'] = '';
            }
            
            
        }
        

        $header = [];
        $header[] = ['日期', 'created_time'];
        $header[] = ['姓名', 'contact'];
        $header[] = ['状态', 'status_msg'];
        $header[] = ['负责人', 'username'];
        $header[] = ['订单号', 'deliver_no'];
        $header[] = ['发货详情', 'error'];
        $header[] = ['物流单号', 'waybill_no'];
        $header[] = ['发货SKU', 'sku'];
        $header[] = ['电话', 'mobile'];
        $header[] = ['详细地址', 'address'];
        $header[] = ['省份', 'city'];
        $header[] = ['市区', 'district'];
        $header[] = ['邮编', 'zip'];
        $header[] = ['邮箱', 'email'];
        $fileName = "export_Autoshipping" . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    /**
     * @desc   自动发货修改
     * @author zhangheng
     * @date   2025-07-04
     */    
    public function edit($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $result = false;
        $id = $data['id'] ?? 0;
        if($id){ 
            $status = (int)$data['status'] ?? 0;
            $status_arr = [0,3];
            if(!in_array($status,$status_arr)){
                return json(DefaultResponse(201, false, '只能修改未发货的订单!', null));
            }
            $data['sku'] = $data['sku'] ?? '';
            $skus = $data['sku'] ?? '';
            if ($skus) {
                // 处理sku 去掉空白
                $skus = trim($skus);
                $skus = str_replace("\r", "", $skus);
                $skus = explode("\n", $skus);
                $skus = implode(",", $skus);
                $data['sku'] = $skus;
            }
            $data['update_time'] = date('Y-m-d H:i:s');  
            $result = Db::name('tik_auto_shipping')->where('id',$id)->update($data);
        }else{
            $data['created_time'] = date('Y-m-d H:i:s');  
            $data['update_time'] = date('Y-m-d H:i:s');  
            $data['sku'] = $data['sku'] ?? '';
            $skus = $data['sku'] ?? '';
            if ($skus) {
                // 处理sku 去掉空白
                $skus = trim($skus);
                $skus = str_replace("\r", "", $skus);
                $skus = explode("\n", $skus);
                $skus = implode(",", $skus);
                $data['sku']  = $skus;
                $skus_arr     = explode(',',$skus);
                $sku          = current($skus_arr);

                $warehouse_id = Db::name('inventory_hwc')
                               ->where(['sku'=>$sku])
                               ->order('new_quantity desc')
                               ->value('warehouse_id');
                $data['warehouse_id']  = $warehouse_id ??3;

            }
            if(!$data['sku']){ 
                return json(DefaultResponse(201, false, '请添加SKU!', null));
            }   
            $result = Db::name('tik_auto_shipping')->insert($data);
        }
        if ($result) {
            return json(DefaultResponse(200, false, '更新成功!', null));
        }
        return json(DefaultResponse(200, false, '更新成功!', null));
    }
    

    public function find($data = [])
    {
        $id = $data['id'] ?? 0;
        if (!$id) {
            return json(DefaultResponse(201, false, '参数错误!', null));
        }
        $where['id'] = $id;
        $row = Db::name('tik_auto_shipping')
            ->where($where)
            ->find();
        if (empty($row)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }
        $skus = $row['sku'] ?? '';
        if ($skus) {
            $skus = explode(',', $skus);
            $skus = implode("\n", $skus);
            $row['sku'] = $skus;
        }
        return json(DefaultResponse(200, true, '获取成功', $row));
    }


    /**
    * @desc    自动发货
    * @author  zhangheng
    */
    public function automatic_shipping($params = [])
    {
        $ids = $params['ids'] ?? [];
        if (!$ids) {
            return json(DefaultResponse(201, false, '请选择要发货的订单!', null));
        }
        $ids = is_array($ids) ? $ids : explode(',', $ids);

        $where[] = ['id', 'in', $ids];
        $lists = Db::name('tik_auto_shipping')
            ->where($where)
            ->select()->toarray();
        $success_num = 0;
        $fail_num = 0;
        foreach ($lists as $k=>$v) { 
            $status = (int)$v['status'] ?? 0;
            $status_arr = [0,3];
            if(!in_array($status,$status_arr)){
                $fail_num++;
            }else{
                $success_num++;
                $this->automatic_shippings($v);
            }
        }
        return json(DefaultResponse(200, true, '操作成功!总共：'.count($lists).'条数据，成功：'.$success_num.'条，失败：'.$fail_num.'条'));
    }

    /**
    * @desc    发货详情
    * @author  zhangheng
    */
    public function automatic_shippings($v)
    {
        $OrderLogic = new OrderLogic();
        $return = $OrderLogic->automaticShipping($v);
        if($return['error'] == "T"){
            Db::name('tik_auto_shipping')
                ->where('id',$v['id'])
                ->update([
                    'status' => 1,
                    'deliver_no' => $return['deliver_no'] ?? "",
                    'error' => $return['content'] ?? "",
                    'update_time' => date('Y-m-d H:i:s'),
                ]);
        }else{
            Db::name('tik_auto_shipping')
                ->where('id',$v['id'])
                ->update([
                    'status' => 3,
                    'deliver_no' => $return['deliver_no'] ?? "",
                    'error' => $return['content'] ?? "",
                    'update_time' => date('Y-m-d H:i:s'),
                ]);
        }
        return true;
    }

    
    /**
     * @desc   导入订单
     * @author zhangheng
     * @date   2025-07-9
     */
    public function import($url,$adminId)
    {
        $data             = Excel::getExcelData('.' . '/' . $url);
        $excelDatas        = isset($data[0]) ? $data[0] : $data;
        if(!$excelDatas)    return json(DefaultResponse(201, false, '暂无数据!', null));
        
        $inserts = [];
        
        $num = 0;
        $success_num = 0;
        $fail_num = 0;
        foreach($excelDatas as $v){
            $num++;
            $type = $v['M'] ?? "";
            switch ($type) {
                case 'KOL':
                    $type = '2';
                    break;
                case 'TIKTOK':
                    $type = '1';
                    break;
                case '海拍':
                    $type = '3';
                    break;
                case 'Billo':
                    $type = '4';
                    break;
                default:
                    $type = '';
            }
            if(empty($type)){
                //失败数量
                $fail_num++;
                continue;
            }
            $adminIds = $v['C'] ?? "";
            $admin = Db::name('system_admin')->where('username',$adminIds)->find();
            if(!empty($admin)){
                $adminId = $admin['id'];
            }
            $created_time = $v['A'] ?? "";
            if(empty($created_time)){
                $created_time = date('Y-m-d H:i:s', time());
            }else{
                $created_time = date('Y-m-d H:i:s', strtotime($created_time));
            }
            //判断是否是数字
            $insert = [
                'admin_id' => $adminId,
                'created_time' => $created_time,
                'update_time' => $created_time,
                'type' => $type,
                'contact' => $v['B'] ?? "",
                'sku' => $v['D'] ?? "",
                'mobile' => $v['E'] ?? "",
                'address' => $v['F'] ?? "",
                'city' => $v['G'] ?? "",
                'district' => $v['H'] ?? "",
                'zip' => $v['I'] ?? "",
                'email' => $v['J'] ?? "",
            ];

            if($insert['sku']){
                  if(strpos($insert['sku'],',') !== false) {
                      $skus = explode(',',$insert['sku']);
                      $sku  = current($skus);
                  }else{
                      $sku  = $insert['sku'];
                  }
                $warehouse_id = Db::name('inventory_hwc')
                            ->where(['sku'=>$sku])
                            ->order('new_quantity desc')
                            ->value('warehouse_id');
                $insert['warehouse_id']  = $warehouse_id ??3;
            }



            $shipping = Db::name('tik_auto_shipping')
                ->where('contact',$insert['contact'])
                ->where('type',$insert['type'])
                ->where('sku',$insert['sku'])
                ->find();
            if(!empty($shipping)){
                $fail_num++;
                continue;
            }
            $inserts[] = $insert;
            $success_num++;
        }
        if(!empty($inserts)){
            Db::name('tik_auto_shipping')->insertAll($inserts);
        }
        return json(DefaultResponse(200, true, '导入成功!总共：'.$num.'条数据，成功：'.$success_num.'条，失败：'.$fail_num.'条'));
    }


    /**
    * @desc    物流轨迹信息
    * @date    2024/12/23
    * @author  zhangheng
    */
    public function trackinfo($params = [])
    {
        $transfer_number = $params['track_number'] ?? '';
        if(empty($transfer_number)){
            return json(DefaultResponse(400, false, '物流单号不能为空'));
        }
        //传订单号 查询物流轨迹以及订单信息
        // $data = $this->TrackQuery($transfer_number);
        
        $data = array();
        $data['trackNum'] = $transfer_number;
        $data2[] = $data;
        $url = "https://apigetway.track718.net/v2/tracking/query";
        // $return = HttpUtil::trackPostUrl718($url, $data2);
        $return = [];
        // halt($return);
        $message = $return['data']['errors'][0]['message'] ?? "";
        if ($message == "Express order number does not exist") {
            (new ApiOrderLogic())->sync_track_register_718($transfer_number);
            return $this->jsonMessage(201, false, "正在注册物流轨迹，请稍后再试");
        }
        if (!empty($message)) {
            return $this->jsonMessage(201, false, "物流API查询错误：".$message);
        }
        // halt($return);
        $track_info = $return['data']['list'] ?? [];
        $info = [];
        $info['latest_sub_status'] = $track_info[0]['latest']['status'] ?? "运输中";
        $info['track_number'] = $transfer_number;
        $info['provider_name'] = $track_info[0]['code']??'USPS';
        $info['provider_country'] = $track_info[0]['country']??'US';
        $info['receive_country'] = $track_info[0]['country']??'US';
        $info['tracking_list'] = $track_info ?? [];
        
        return $this->jsonMessage(200, true, '获取成功', $info);
    }
    
    
    /**
    * @desc    物流轨迹信息
    * @date    2024/12/24
    * @author  zhangheng
    */
    public function TrackQuery($track_number)
    {
        $where[] = ['track_number', '=', $track_number];
        $info = Db::name('order_track')
            ->field('*')
            ->where($where)
            ->find();
        $info['latest_sub_status'] = "运输中";
        $info['track_number'] = $track_number;
        $info['provider_name'] = $info['provider_name']??'USPS';
        $info['provider_country'] = $info['provider_country']??'US';
        $info['receive_country'] = $info['receive_country']??'US';
        $info['tracking_list'] = $info['tracking_list'] ?? [];
        if (!empty($info['tracking_list'])) {
            $info['tracking_list']= json_decode($info['tracking_list'],true);
        }
        return $info;
    }

}